﻿using HomeCloudStorageSystem.DataBase;
using HomeCloudStorageSystem.Dtos;
using HomeCloudStorageSystem.Models;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.IdentityModel.Tokens;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Transactions;

namespace HomeCloudStorageSystem.Services
{
    public class FileDirectoryRepository : IFileDirectoryRepository
    {
        private readonly AppDbContext _context;
        public FileDirectoryRepository(AppDbContext context)
        {
            _context = context;
        }
        public IEnumerable<FilesAndDirectorysDto> GetFileDirectorys(int? parentId)
        {
            var fileDirectorysToFilesAndDirectorysDto = _context.FileDirectory.Where(n => n.ParentId == parentId)
                .Select(i => new FilesAndDirectorysDto
            {
                Id = i.Id,
                Name = i.DirectoryName,
                ExtName = "",
                ParentId = i.ParentId,
                CreateTime = i.CreateTime,
                ChildsNum = (_context.FileDirectory.Where(f => f.ParentId == i.Id).Count() <= 0? 0:_context.FileDirectory.Where(f => f.ParentId == i.Id).Count())
                    + (_context.FileInfo.Where(f => f.DirectoryId == i.Id).Count() <= 0? 0: _context.FileInfo.Where(f => f.DirectoryId == i.Id).Count()),
            });
            var fileInfosToFilesAndDirectorysDto = _context.FileInfo.Where(n => n.DirectoryId == parentId)
                .Select(n => new FilesAndDirectorysDto
                {
                    Id = n.Id,
                    Name = n.FileName,
                    ExtName = n.ExtName,
                    ParentId = n.DirectoryId,
                    CreateTime = n.UploadTime,
                    ChildsNum = 0,
                });
            var filesAndDirectorysDto = fileDirectorysToFilesAndDirectorysDto.Concat(fileInfosToFilesAndDirectorysDto);


            return filesAndDirectorysDto;
        }
        public FileDirectory GetFileDirectoryById(int id)
        {
            return _context.FileDirectory.FirstOrDefault(n => n.Id == id);
        }
        public string AddFileDirectory(FileDirectoryForCreationDto fileDirectoryForCreationDto)
        {
            var transaction = _context.Database.BeginTransaction();
            bool flag = false;
            string fullPath = null;
            try
            {
                if (fileDirectoryForCreationDto.ParentId == null || fileDirectoryForCreationDto.ParentId <= 0)
                {
                    fileDirectoryForCreationDto.DirectoryPath = @"../../家庭云盘系统文件夹/上传文件/";
                }
                if (fileDirectoryForCreationDto.ParentId != null && fileDirectoryForCreationDto.ParentId > 0)
                {
                    var parentDirectory = _context.FileDirectory.Where(n => n.Id == fileDirectoryForCreationDto.ParentId).FirstOrDefault();
                    fileDirectoryForCreationDto.DirectoryPath = parentDirectory.DirectoryPath + parentDirectory.DirectoryName + "/";
                }
                fullPath = Path.Combine(fileDirectoryForCreationDto.DirectoryPath + fileDirectoryForCreationDto.DirectoryName);
                if (Directory.Exists(fullPath))
                {
                    return $"目录 {fileDirectoryForCreationDto.DirectoryName} 已经存在";
                }
                Directory.CreateDirectory(fullPath);
                flag = true;

                var fileDirectoryToSave = new FileDirectory
                {
                    ParentId = fileDirectoryForCreationDto.ParentId <= 0 ? 0 : fileDirectoryForCreationDto.ParentId,
                    DirectoryName = fileDirectoryForCreationDto.DirectoryName,
                    DirectoryPath = fileDirectoryForCreationDto.DirectoryPath,
                    CreateTime = DateTime.Now.ToString("yyyy-MM-dd"),
                    Creator = fileDirectoryForCreationDto.Creator,
                };
                _context.FileDirectory.Add(fileDirectoryToSave);
                _context.SaveChanges();

                transaction.Commit();
                return "添加目录成功";
            }
            catch
            {
                if (flag)
                {
                    var filePath = Path.Combine(fullPath, fileDirectoryForCreationDto.DirectoryName);
                    Directory.Delete(filePath);
                }
                transaction.Rollback();
                return "添加目录失败";
            }
        }
        public string RemoveFileDirectory(FileDirectory fileDirectory)
        {
            var transaction = _context.Database.BeginTransaction();
            string fullPath = fileDirectory.DirectoryPath + fileDirectory.DirectoryName;
            try
            {
                var files = Directory.GetFiles(fullPath);
                var directorys = Directory.GetDirectories(fullPath);
                if (files.Length > 0 || directorys.Length > 0)
                {
                    return $"目录“{fileDirectory.DirectoryName}”中存在成员，不能删除。";
                }
                Directory.Delete(fullPath);
                _context.FileDirectory.Remove(fileDirectory);
                _context.SaveChanges();
                transaction.Commit();

                return "删除成功";
            }
            catch
            {
                Directory.CreateDirectory(fullPath);
                transaction.Rollback();
                return "删除失败";
            }
        }
        public bool Save()
        {
            return (_context.SaveChanges() > 0);
        }
    }
}
